<!--
 * @Author: LiZhiWei
 * @Date: 2025-07-14 08:58:30
 * @LastEditors: wjc
 * @LastEditTime: 2025-10-28 14:28:08
 * @Description: 
-->
<template>
  <div class="pt-40px pb-80px relative">
    <Former
      v-loading="loading"
      :cancel-button="false"
      :data="editFormer.data"
      :fields="editFormer.fields"
      :loading="formLoading"
      :validate="editFormer.validate"
      max-height="auto"
      v-bind="$attrs"
      @on-confirmed="onConfirmed"
    >
      <template v-for="(_, name) in $slots" #[name]="slotData">
        <slot :name="name" v-bind="slotData"></slot>
      </template>
    </Former>
  </div>
</template>

<script setup lang="ts">
  import { useEditor } from '#/hooks/useEditor'

  defineOptions({
    name: 'EditorEmbed',
  })

  const props = withDefaults(
    defineProps<{
      entity?: string
      entityId?: number | string
      message?: string
      requestUrl?: RequestUrl
    }>(),
    {
      entityId: '',
      entity: '',
      requestUrl: () => ({}),
      message: '编辑成功',
    }
  )

  const emits = defineEmits<{
    (e: 'on-updated', res: object): void
  }>()

  // 使用编辑hook
  const {
    loading,
    formLoading,
    editFormer,
    getEditFormWithId,
    getEditFormWith,
    handleUpdate,
    handleUpdateWith,
  } = useEditor({
    entity: props.entity,
    mode: 'embed',
    message: props.message,
  })

  const onConfirmed = (form: object) => {
    const onUpdated = (res: any) => {
      emits('on-updated', res.data)
    }

    if (props.requestUrl?.update) {
      return handleUpdateWith(
        {
          update: props.requestUrl.update as string,
          params: { ...props.requestUrl.params, ...form },
        },
        onUpdated
      )
    }

    return handleUpdate(form, props.entityId, onUpdated)
  }

  const loadEditForm = () => {
    if (props.requestUrl?.edit) {
      return getEditFormWith(props.requestUrl)
    }
    return getEditFormWithId(props.entityId)
  }

  onMounted(() => {
    loadEditForm()
  })
</script>
